<template>
  <div class="settings-container" v-loading="loading">
    <div class="page-title">系统设置
      <el-switch
          v-model="settingStore.useDb"
          class="db-switcher"
          active-text="读取数据库"
          inactive-text="实时模式"
          @change="onDbModeChange"
      />
    </div>

    <el-form :model="form" :rules="rules" ref="formRef" class="form-container" label-position="top">
      <!-- 车辆控制设置 -->
      <div class="form-section">
        <div class="section-title vehicle">车辆控制设置</div>
        <el-form-item label="车辆IP地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入车辆IP地址" ></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆控制端口" prop="drivePort">
              <el-input v-model.number="form.drivePort" placeholder="请输入端口号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分析程序端口" prop="analysisPort">
              <el-input v-model.number="form.analysisPort" placeholder="请输入端口号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 云端平台设置 -->
      <div class="form-section">
        <div class="section-title cloud">云端平台设置</div>
        <el-form-item label="云端平台地址" prop="cloudUrl">
          <el-input v-model="form.cloudUrl" placeholder="请输入云端平台地址"></el-input>
        </el-form-item>
      </div>

      <!-- 摄像头设置 -->
      <div class="form-section">
        <div class="section-title camera">摄像头设置</div>
        <div v-for="i in 4" :key="i" class="camera-group">
          <div class="camera-title">摄像头{{ i }}</div>
          <el-form-item :label="`摄像头${i}地址`">
            <el-input v-model="(form as any)[`cam${i}`]" placeholder="请输入摄像头地址"></el-input>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="`摄像头${i}账号`">
                <el-input v-model="(form as any)[`username${i}`]" placeholder="请输入账号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="`摄像头${i}密码`">
                <el-input v-model="(form as any)[`password${i}`]" type="password" show-password placeholder="请输入密码"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>

    <div class="btn-group">
      <el-button @click="onCancel" class="btn">取消</el-button>
      <el-button type="primary" @click="onSubmit" class="btn btn-primary" :loading="saving">保存设置</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useSetting } from '@/stores/setting';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { useRouter } from 'vue-router';
import type { AgvConfig } from '@/axios/types';
import { getConfig, updateConfig, upsertConfigDb } from '@/axios/api';

const settingStore = useSetting();
const router = useRouter();
const formRef = ref<FormInstance>();
const saving = ref(false);
const loading = ref(true);

const form = reactive<AgvConfig>({ ...settingStore.config });

const rules = reactive<FormRules>({
  host: [
    { required: true, message: '请输入车辆IP地址', trigger: 'blur' },
    {
      pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: '请输入有效的IP地址',
      trigger: 'blur'
    }
  ],
  drivePort: [
    { required: true, message: '请输入车辆控制端口', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '请输入有效的端口号 (1-65535)', trigger: 'blur' }
  ],
  analysisPort: [
    { required: true, message: '请输入分析程序端口', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '请输入有效的端口号 (1-65535)', trigger: 'blur' }
  ],
  cloudUrl: [
    { required: true, message: '请输入云端平台地址', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ]
});

const loadConfig = async () => {
  loading.value = true;
  try {
    const res = await getConfig();
    if (res.data) {
      settingStore.updateConfig(res.data);
      Object.assign(form, settingStore.config);

      // 同步到本地 DB
      if (!settingStore.useDb) {
        upsertConfigDb(res.data).catch(err => console.error('同步配置到DB失败', err));
      }
    }
  } catch (error) {
    ElMessage.error('加载配置失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      saving.value = true;
      try {
        await updateConfig(form);
        settingStore.updateConfig(form);
        ElMessage.success('设置已保存成功！');
        ElMessageBox.confirm('是否返回系统初始化页面重新检测？', '保存成功', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          router.push('/');
        }).catch(() => {});
      } catch (error) {
        ElMessage.error('保存配置失败');
        console.error(error);
      } finally {
        saving.value = false;
      }
    } else {
      ElMessage.error('请检查并修正表单中的错误');
    }
  });
};

const onCancel = () => {
  ElMessageBox.confirm('确定要取消设置吗？未保存的更改将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    Object.assign(form, settingStore.config);
    formRef.value?.clearValidate();
    ElMessage.info('操作已取消');
    router.push('/')
  }).catch(() => {});
};

const onDbModeChange = () => {
  // 重新加载配置以切换数据源
  loadConfig();
};

onMounted(() => {
  loadConfig();
});
</script>

<style scoped>
.settings-container {
  max-width: 600px;
  margin: 20px auto;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  position: relative;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 30px;
  text-align: center;
  color: #333;
  padding-bottom: 15px;
  border-bottom: 2px solid #409eff;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-section {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #409eff;
  display: flex;
  align-items: center;
}
.section-title.vehicle::before { content: "🚛"; margin-right: 8px; }
.section-title.cloud::before { content: "☁️"; margin-right: 8px; }
.section-title.camera::before { content: "📹"; margin-right: 8px; }

.camera-group {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  background: white;
}

.camera-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #666;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.btn-group {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.btn {
  padding: 10px 24px;
  font-size: 14px;
  min-width: 80px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  color: #333;
}

.db-switcher {
  position: absolute;
  top: 20px;
  right: 20px;
}
</style>